//订单相关处理方法
var wineApp = wineApp || {};
wineApp.orderutil = (function() {
    var wechatPaymentKey = wineApp.CONFIG.PAYMENT.wechat.signKey;
    var wechatAppId = wineApp.CONFIG.PAYMENT.wechat.appid;
    var notifyUrl = wineApp.CONFIG.PAYMENT.notifyUrl;
    var wechatMchId = wineApp.CONFIG.PAYMENT.wechat.mch_id;
    var createOrder = function(order, prodList, paymenttype, catrids) {
        var ajaxUrl = wineApp.CONFIG.API.createorder;

        wineApp.ajax.post(ajaxUrl, {
            order: order,
            products: prodList,
            cartids: catrids
        }).done(function(data) {
            var orderId = data.orderid;
            console.log('创建订单成功');
            layer.open({
                content: '请选择支付方式',
                btn: ['支付宝', '微信支付'],
                skin: 'footer',
                yes: function(index) {
                    wineApp.orderutil.alipayment(data);
                    layer.close(index);
                },
                no: function() {
                    wineApp.orderutil.wechatPayment(data);
                }

            });
            //window.location.href = "order_list.html";
            //调用支付宝或者微信支付
        })
    }
    var createProdObjToStorage = function(prodList, from) {
            //创建产品信息数据，等订单完成，要删除临沭存储
            var key = wineApp.tool.getKey("selectedPlan");
            var comeFrom = wineApp.tool.getKey("from");

            wineApp.localStorage.remove(key);
            wineApp.localStorage.remove(comeFrom);

            wineApp.localStorage.set(key, prodList);
            //用于识别是在产品明细还是购物车创建产品信息
            wineApp.localStorage.set(comeFrom, from);
        }
        //创建订单对象
    var createOrderInfo = function() {

    }
    var getProdNameList = function() {
        var key = wineApp.tool.getKey("selectedPlan");
        var planList = wineApp.localStorage.get(key);
        var body = _(planList).map("wineName").join(",");
        return body;
    }
    var wechatPayment = function(data) {
        processWechatPayment(data)
    }
    var alipayment = function(data) {
        var body = getProdNameList();
        window.alipay.pay({
            "subject": data.orderid,
            "body": body,
            "price": data.sum,
            "tradeNo": data.orderid,
            "notifyUrl": notifyUrl
        }, function(msgCode) {
            console.log(msgCode);
            clearStorage();
            window.location.href = "order_list.html";
        }, function(msg) {
            console.log(msg)
            showMessage('付款失败:' + msg);
        })
    }

    var sortParam = function(data) {
        var keys = _.keys(data);
        var sortedKeys = _.sortBy(keys, function(key) {
            return key;
        });
        var param = _.chain(sortedKeys).map(function(key) {
            var obj = data[key];
            if (_.isObject(obj)) {
                obj = JSON.stringify(obj)
            }
            return key + "=" + obj;
        }).join('&').value();
        console.log('befor sign:.%O', param);
        return param;
    }
    var signParam = function(data) {
        var signStr = sortParam(data) + "&key=" + wechatPaymentKey;
        return CryptoJS.MD5(signStr).toString().toUpperCase();
    }
    var buildWechatPaymentReq = function(order) {
        var body = getProdNameList(order);
        var random = wineApp.tool.randomString(16);
        var data = {
            appid: wechatAppId,
            mch_id: wechatMchId,
            nonce_str: random,
            body: '安东尼奥酒业-' + body,
            out_trade_no: order.orderid,
            total_fee: order.sum * 100, //微信支付用分表示金额，3000代表：30元
            spbill_create_ip: '8.8.8.8',
            notify_url: notifyUrl,
            trade_type: 'APP'
        }
        return {
            sign: signParam(data),
            data: data
        };


    }
    var getPaymentXML = function(order) {
        var req = buildWechatPaymentReq(order);
        var template = "<${key}>${value}</${key}>";
        var xml = "";
        _.forEach(req.data, function(value, key) {
            xml += _.template(template)({
                key: key,
                value: value
            })
        });
        xml += "<sign>" + req.sign + "</sign>";
        xml = "<xml>" + xml + "</xml>";
        return xml;
    }
    var processWechatPayment = function(order) {
        var ajaxUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        var xml = getPaymentXML(order);
        console.log("xml:" + xml);
        doAjax(ajaxUrl, "POST", xml).then(function($xml) {
            return $xml.find("prepay_id").text()
        }).then(function(prepay_id) {
            var param = {
                appid: wechatAppId,
                partnerid: wechatMchId, // merchant id
                prepayid: prepay_id, // prepay id
                noncestr: wineApp.tool.randomString(16), // nonce
                timestamp: _.now(), // timestamp
                package: "Sign=WXPay"
            }
            param['sign'] = signParam(param);
            Wechat.sendPaymentRequest(param, function() {
                console.log("Success");
                clearStorage();
                window.location.href = "order_list.html";
            }, function(reason) {
                showMessage('付款失败:' + reason);
            });
        });
    }

    var doAjax = function(url, method, params) {
        var async = true;
        var deferred = $.Deferred();
        $.ajax({
                url: url,
                type: method,
                dataType: 'text',
                async: async,
                cache: false,
                contentType: 'application/xml',
                data: params
            }).done(function(data) {
                console.log('response from server:%O', data)
                var xmlDoc = $.parseXML(data);
                var $xml = $(xmlDoc);
                deferred.resolve($xml);
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                console.log('jqXHR:%O', jqXHR)
                var xmlDoc = $.parseXML(jqXHR.responseText);
                var $xml = $(xmlDoc);
                var message = "支付错误:" + $xml.find('return_msg').text();
                showMessage(message);
                deferred.reject($xml);
            });
        return deferred.promise();
    }

    var showMessage = function(message) {
        layer.open({
            content: message,
            btn: '确定'
        })
    }

    var clearStorage = function() {
        var comeFrom = wineApp.tool.getKey("from");
        var selectedPlanKey = wineApp.tool.getKey("selectedPlan");
        wineApp.localStorage.remove(comeFrom);
        wineApp.localStorage.remove(selectedPlanKey);
    }

    var loadOrderInfoWithOrderId = function(orderId) {
        clearStorage();
        var ajaxUrl = wineApp.CONFIG.API.myorderdetail;
        return wineApp.ajax.post(ajaxUrl, {
            orderid: orderId
        }).then(function(data) {
            var orderlist = data.order.details;
            var selectedPlan = [];
            _.forEach(orderlist, function(detail) {
                var obj = {
                    count: detail.num,
                    prodid: detail.prodid,
                    ammount: 0,
                    wineName: detail.proname,
                    wineImg: wineApp.common.getImgName(detail.titleimg),
                    winePrice: detail.price,
                    wineOverseasPrice: detail.oprice,
                    id: detail.prodid
                }
                selectedPlan.push(obj);
            })
            wineApp.orderutil.createProdObjToStorage(selectedPlan, 'orderdetail');
            return data.order;
        })
    }
    return {
        createOrder: createOrder,
        createProdObjToStorage: createProdObjToStorage,
        wechatPayment: wechatPayment,
        alipayment: alipayment,
        loadOrderInfoWithOrderId: loadOrderInfoWithOrderId,
        clearStorage: clearStorage
    }
})();